package com.gzit.activity;

import android.app.Activity;
import android.app.TabActivity;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.RadioButton;
import android.widget.TabHost;

/**
 * 基于radiobutton切换的tabhost
 * 
 * @author teddy
 * 
 */
public abstract class GzitTabHostActivity extends TabActivity {

	protected GzitTabHostActivity that = this;

	private TabHost mHost;

	protected Intent[] intents;

	// 由子类提供内嵌的activity类
	protected abstract Class<Activity>[] getHostActivitys();

	// 由子类提供radioBtnId的id
	protected abstract int[] getRadioBtnIds();

	public Intent onCreateIntent(Class<Activity> activity) {
		return new Intent(this, activity);

	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		init();
	}

	protected void init() {
		this.createTabIntents();
		this.initRadioBtn();
	}

	protected void createTabIntents() {

		this.mHost = getTabHost();
		Class<Activity>[] activities = this.getHostActivitys();
		this.intents = new Intent[activities.length];
		for (int i = 0; i < intents.length; i++) {
			intents[i] = onCreateIntent(activities[i]);
			this.mHost.addTab(buildTabSpec("tab" + i, "tab", (Drawable) null,
					intents[i]));
		}

	}

	private OnCheckedChangeListener switchTabListener = new OnCheckedChangeListener() {

		@Override
		public void onCheckedChanged(CompoundButton buttonView,
				boolean isChecked) {

			if (isChecked) {
				int rid = buttonView.getId();

				int[] ids = that.getRadioBtnIds();
				for (int i = 0; i < ids.length; i++) {
					if (rid == ids[i]) {// 找到对应的被按中的radio
						that.mHost.setCurrentTabByTag("tab" + i);
						break;
					}
				}
			}

		}

	};

	private void initRadioBtn() {
		for (int id : this.getRadioBtnIds()) {
			((RadioButton) findViewById(id))
					.setOnCheckedChangeListener(switchTabListener);

		}

	}

	protected TabHost.TabSpec buildTabSpec(String tag, String resLabel,
			Drawable resIcon, final Intent content) {
		return this.mHost.newTabSpec(tag).setIndicator(resLabel, resIcon)
				.setContent(content);
	}
}
